﻿using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;

namespace Darius.API.Application.Commands.Order
{
    public class ProductSearchHandler : IRequestHandler<ProductSearchCommand, ResultPage<Product>>
    {
        private readonly IBaseRepositorys<Product> productRepository;
        private readonly ILogger<ProductSearchCommand> logger;

        public ProductSearchHandler(IBaseRepositorys<Product> productRepository, ILogger<ProductSearchCommand> logger)
        {
            this.productRepository = productRepository;
            this.logger = logger;
        }
        /// <summary>
        /// 查询产品信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultPage<Product>> Handle(ProductSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new ResultPage<Product>() { Code=(int)CodeEnum.search};
            var res= productRepository.GetAll().ToList();
            if (!string.IsNullOrEmpty(request.ProductNumber))
            {
                res=res.Where(x => x.ProductNumber.Contains(request.ProductNumber)).ToList();
            }
            if (!string.IsNullOrEmpty(request.ProductName))
            {
                res=res.Where(x => x.ProductName.Contains(request.ProductName)).ToList();
            }
            result.totalCount = res.Count;
            result.totalPage = (int)Math.Ceiling((result.totalCount * 1.0) / request.Psize);
            result.Data=res.OrderBy(x=>x.ProductId).Skip((request.Pindex-1)*request.Psize).Take(request.Psize).ToList();
            result.Messege = "列表查询成功";
            logger.LogInformation(result.Messege);
            return result;
        }
    }
}
